//
//  RecommendViewController.m
//  TodayFirstNews
//
//  Created by 向祖华 on 16/3/2.
//  Copyright © 2016年 向祖华. All rights reserved.
//

#import "RecommendViewController.h"
#import "RecommendTableViewCell.h"
#import "RecommendModel.h"
#import "RecommendTableViewCell_ThreeImage.h"
#import "DownloadImageOperation.h"
#import "RecommendTableViewCell_noImage.h"
#import "DetailViewController.h"
#import "SearchViewController.h"
#import <MJRefresh/MJRefresh.h>


static NSString * const kRecommendUrl = @"http://ic.snssdk.com/2/article/v17/stream/?item_type=4&iid=2321205973&min_behot_time=0&count=20&category=news&image=1&detail=1&tt_from=auto&ac=wifi&channel=App%20Store&app_name=news_article&aid=13&version_code=3.5.1&device_platform=iphone&os_version=5.1.1&device_type=iPhone%204&openudid=2bbb47b07ae4be4484bd1c5e93315c8196787c2f";
//记录tableView的滑动方向
static BOOL scrollUp = NO;

@interface RecommendViewController ()<UITableViewDataSource,UITableViewDelegate,DownloadImageOperationDelegate>

@property(nonatomic,strong)NSMutableArray* allDataArray;//存储数据
@property(nonatomic,strong)NSOperationQueue * queue;//队列
@property(nonatomic,strong)NSMutableArray * refreshDataArr;
@property(nonatomic,strong)UIRefreshControl * refrechC;//刷新控制器
@property(nonatomic,assign)CGRect searchFrame;
@property(nonatomic,assign)CGRect tableViewFrame;
@end



@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //处理数据
    [self getData];
    //设置一个view添加搜索框
    self.searchFrame = CGRectMake(0, 0, kScreenWidth, 30);
    self.tableViewFrame = CGRectMake(0, 30, kScreenWidth, kScreenHeight-64);
    //创建底视图
    self.searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0)];
    
    self.searchView.backgroundColor = [UIColor colorWithRed:200/225.0 green:200/225.0 blue:200/225.0 alpha:1];
    //创建button
    UIButton* headerView  = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [headerView setFrame:CGRectMake(20, 5, kScreenWidth - 40, 20)];
    headerView.layer.cornerRadius = 10;
    headerView.layer.borderWidth = 0.01;
    //设置Button的文字
    [headerView setTitle:@"搜索..." forState:(UIControlStateNormal)];
    headerView.titleLabel.font = [UIFont systemFontOfSize:13];
    [headerView setTitleColor:[UIColor colorWithRed:100/225.0 green:100/225.0 blue:100/225.0 alpha:1] forState:(UIControlStateNormal)];
    //使文字距离左边框保持10个像素的距离。
    [headerView setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    //UIButton的title居左对齐
    headerView.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;//左对齐
    //Button的点击事件
    [headerView addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    headerView.backgroundColor = [UIColor whiteColor];
    
    [self.searchView addSubview:headerView];
    [self.view addSubview:self.searchView];
    
    //设置tableView的大小
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64) style:(UITableViewStylePlain)];
    
    [self.view addSubview:self.tableView];
    //设置代理
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    
    //tableViewCell的注册
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendTableViewCell" bundle:nil] forCellReuseIdentifier:@"RecommendTableViewCell_smallImage"];//一张图片的cell
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendTableViewCell_ThreeImage" bundle:nil] forCellReuseIdentifier:@"RecommendTableViewCell_ThreeImage"];//三张图片的cell
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendTableViewCell_noImage" bundle:nil] forCellReuseIdentifier:@"RecommendTableViewCell_noImage"];//无图片
    //cell自适应高度
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 2;
    
    //添加轻扫手势，展现搜索框
    UISwipeGestureRecognizer * swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipAction)];
    swip.direction = UISwipeGestureRecognizerDirectionUp;
    [self.tableView addGestureRecognizer:swip];
    //下拉刷新数据
    [self setupRefresh];
}
#pragma mark - 轻扫手势控制搜索框
-(void)swipAction{
    [self.tableView.tableHeaderView setHidden:YES];
    NSLog(@"滑了一下");
    
}
    
#pragma mark - 创建下拉刷新功能
-(void)setupRefresh{
    //创建下拉刷新控制器
    self.refrechC = [[UIRefreshControl alloc] init];
    //添加刷新事件
    [self.refrechC addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventValueChanged];
    //添加到tableView
    [self.tableView addSubview:self.refrechC];
}
-(void)refreshAction{
    NSLog(@"运行到我这");
    [self.allDataArray removeAllObjects];
    //请求数据
    NSURL * url = [NSURL URLWithString:kRecommendUrl];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    NSURLSession * session = [NSURLSession sharedSession];
    [request setHTTPMethod:@"GET"];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//            [self.refreshDataArr removeAllObjects];//清空刷新存储数组
            
            for (NSDictionary* dicotionary in dic[@"data"]) {
                RecommendModel*model = [[RecommendModel alloc] init];
                [model setValuesForKeysWithDictionary:dicotionary];
                model.comment_count = dicotionary[@"comment_count"];
                //取到一张图片的连接
                model.image_one = [dicotionary[@"middle_image"] objectForKey:@"url"];
                //取到三张图片的链接
                NSArray*imageArr = [NSArray arrayWithArray:dicotionary[@"image_list"]];
                [model setValue:imageArr forKey:@"image_list"];
                
                if (imageArr.count) {
                    model.image_left = [imageArr[0] objectForKey:@"url"];
                    model.image_middle = [imageArr[1] objectForKey:@"url"];
                    model.image_right = [imageArr[2] objectForKey:@"url"];
                }

                [self.allDataArray addObject:model];
            }
            
        }
        else{
            NSLog(@"刷新失败");
            [self.refrechC endRefreshing];
        }
        [self performSelectorOnMainThread:@selector(mainThread1) withObject:nil waitUntilDone:YES];
    }];
    [task resume];
}
-(void)mainThread1{
    //数据去重？？？？
//    NSMutableArray * tempArr = [NSMutableArray array];
//    for (int i = 0; i < self.refreshDataArr.count; i++) {
//        RecommendModel * model =  self.refreshDataArr[i];
//        for (int j = 0; j < self.allDataArray.count; j++) {
//            RecommendModel * model1 = self.allDataArray[j];
//            NSLog(@"%@,%@",model1.title,model.title);
//            if ([model.image_one isEqualToString:model1.image_one]) {
//                [tempArr addObject:model1];
//                
//            }else{
//                continue;
//            }
//        }
//    }
//    NSLog(@"%@",self.allDataArray);
//    NSRange rang = NSMakeRange(0, tempArr.count);
//    NSIndexSet * set = [[NSIndexSet alloc]initWithIndexesInRange:rang];
//    [self.allDataArray insertObjects:tempArr atIndexes:set];
//    //刷新请求下来的数据加载到总数组中
//    [self.refreshDataArr removeAllObjects];
    [self.tableView reloadData];
    [self.refrechC endRefreshing];

}
#pragma mark - 处理数据
-(void)getData{
    NSURL * url = [NSURL URLWithString:kRecommendUrl];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    NSURLSession * session = [NSURLSession sharedSession];
    [request setHTTPMethod:@"GET"];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            for (NSDictionary* dicotionary in dic[@"data"]) {
                
                RecommendModel*model = [[RecommendModel alloc] init];
                [model setValuesForKeysWithDictionary:dicotionary];
                model.comment_count = dicotionary[@"comment_count"];//评论数
                //取到一张图片的连接
                model.image_one = [dicotionary[@"middle_image"] objectForKey:@"url"];

                //取到三张图片的链接
                NSArray*imageArr = [NSArray arrayWithArray:dicotionary[@"image_list"]];
                [model setValue:imageArr forKey:@"image_list"];
//                NSLog(@"%@",imageArr);
                if (imageArr.count) {
                    model.image_left = [imageArr[0] objectForKey:@"url"];
                    model.image_middle = [imageArr[1] objectForKey:@"url"];
                    model.image_right = [imageArr[2] objectForKey:@"url"];                }
                [self.allDataArray addObject:model];
            }
            
        }
        [self performSelectorOnMainThread:@selector(mainThread) withObject:nil waitUntilDone:YES];
        
    }];
    [task resume];
}

-(void)mainThread{
    [self.tableView reloadData];
}


#pragma mark - tableView代理方法实现
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.allDataArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //
    RecommendModel * model = self.allDataArray[indexPath.row];
    
    //判断是那种cell
    if (!model.image_left) {
        if (!model.image_one) {
            RecommendTableViewCell_noImage*cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendTableViewCell_noImage" forIndexPath:indexPath];
            cell.titl.text = model.title;
            cell.source.text = model.source;
            cell.type.text = nil;
            //评论处理
            NSString* commentStr = [NSString stringWithFormat:@"  %@评论 ",model.comment_count];
            cell.comment_count.text =commentStr;
            //处理发布时间
            double publishTime = [model.publish_time longLongValue];
            cell.publish_time.text = [self setPublishTime:publishTime];
            return cell;
        }
        else{
        RecommendTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendTableViewCell_smallImage" forIndexPath:indexPath];
        cell.titl.text = model.title;
        cell.source.text = model.source;
        cell.type.text = nil;
        //评论处理
        NSString* commentStr = [NSString stringWithFormat:@"  %@评论 ",model.comment_count];
        cell.comment_count.text =commentStr;
        
        //处理图片
        [self downLoadImageWithUrlString:model.image_one indexPath:indexPath imageTag:cell.image.tag];
        //处理发布时间
        double publishTime = [model.publish_time longLongValue];
        cell.publish_time.text = [self setPublishTime:publishTime];
        
        return cell;
        }
    }else
    {
        RecommendTableViewCell_ThreeImage * cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendTableViewCell_ThreeImage" forIndexPath:indexPath];
        cell.titl.text = model.title;
        cell.source.text = model.source;
        cell.type.text = nil;
        //评论数
        cell.comment_count.text = [NSString stringWithFormat:@"  %@评论 ",model.comment_count];
        //处理发布时间
        double publishTime = [model.publish_time longLongValue];
        cell.publish_time.text = [self setPublishTime:publishTime];
        
        //处理图片
        [self downLoadImageWithUrlString:model.image_left indexPath:indexPath imageTag:cell.leftImage.tag];
        [self downLoadImageWithUrlString:model.image_middle indexPath:indexPath imageTag:cell.middleImage.tag];
        [self downLoadImageWithUrlString:model.image_right indexPath:indexPath imageTag:cell.rightImage.tag];

        return cell;
    }
}
//点击细胞的事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RecommendModel * model = self.allDataArray[indexPath.row];
    DetailViewController*detailVC = [[DetailViewController alloc] init];
    [detailVC setValue:model.url forKey:@"url"];
    [self presentViewController:detailVC animated:YES completion:nil];
}
//返回header
//-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    //创建底视图
//    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
//    view.backgroundColor = [UIColor colorWithRed:200/225.0 green:200/225.0 blue:200/225.0 alpha:1];
//    //创建button
//    UIButton* headerView  = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    [headerView setFrame:CGRectMake(20, 5, kScreenWidth - 40, 20)];
//    headerView.layer.cornerRadius = 10;
//    headerView.layer.borderWidth = 0.01;
//    //设置Button的文字
//    [headerView setTitle:@"搜索..." forState:(UIControlStateNormal)];
//    headerView.titleLabel.font = [UIFont systemFontOfSize:13];
//    [headerView setTitleColor:[UIColor colorWithRed:100/225.0 green:100/225.0 blue:100/225.0 alpha:1] forState:(UIControlStateNormal)];
//    //使文字距离左边框保持10个像素的距离。
//    [headerView setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
//    //UIButton的title居左对齐
//    headerView.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;//左对齐
//    //Button的点击事件
//    [headerView addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
//    headerView.backgroundColor = [UIColor whiteColor];
//    
//    [view addSubview:headerView];
//    return view;
//    
//}
//返回header的高度
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if (section == 0) {
//        return 30;
//    }else{
//        return 0;
//    }
//}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //Selected index's color changed.
    static float newY = 0;
    static float oldY = 0;
    newY= scrollView.contentOffset.y ;
    if (newY != oldY ) {
        //UP-YES,DOWN-NO
        if ((oldY - newY <=3)&&(oldY - newY>=0)&&newY<=2) {
            scrollUp = NO;
            [UIView animateWithDuration:0.5 animations:^{
                self.tableView.frame = self.tableViewFrame;
                self.searchView.frame = self.searchFrame;
            }];
            NSLog(@"下滑");
        }else if(newY - oldY >= 1){
            scrollUp = YES;
            [UIView animateWithDuration:0.5 animations:^{
                self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
                self.searchView.frame = CGRectMake(0, 0, kScreenWidth, 0);
            }];
            NSLog(@"上滑");
        }
        oldY = newY;
    }
 
}


#pragma mark -








/**
 *  搜索button的点击事件
 */
-(void)buttonAction{
    SearchViewController * searchVC = [[SearchViewController alloc] init];
    [self presentViewController:searchVC animated:YES completion:nil];
}
#pragma mark - 私有封装方法
/**
 *  将时间串与当前时间距1970地秒数对比，得到两者的间隔
 *
 *  @param timeSeconds 时间串
 *
 *  @return 返回时间间隔
 */
-(NSString*)setPublishTime:(double)timeSeconds{
    
    NSDate* nowDate = [NSDate date];
    NSTimeInterval timeInterval = [nowDate timeIntervalSince1970];

    double time = (timeInterval - timeSeconds)/60;
    NSString * timeStr = nil;
    if (time >0&&time < 10) {
        timeStr = @" 10分钟前";
    }else if(time >10&&time < 20){
        timeStr = @" 20分钟前";
    }else if (time >=20&&time < 30){
        timeStr = @" 30分钟前";
    }else if(time >=30&&time < 40){
        timeStr = @" 40分钟前";
    }else if(time >=40&&time < 50){
        timeStr = @" 50分钟前";
    }else if(time >=50&&time < 60){
        timeStr = @" 1小时前";
    }else if(time >=60&&time < 120){
        timeStr = @" 2小时前";
    }else if(time >=120&&time < 180){
        timeStr = @" 3小时前";
    }else if(time >=180&&time < 240){
        timeStr = @" 4小时前";
    }
    return timeStr;

}
//图片处理封装
-(void)downLoadImageWithUrlString:(NSString*)urlString indexPath:(NSIndexPath*)indexPath imageTag:(NSInteger)imageTage{
    //创建图片下载操作
    DownloadImageOperation * downloadIamge = [[DownloadImageOperation alloc] init];
    downloadIamge.url = urlString;
    downloadIamge.indexPath = indexPath;
    downloadIamge.imageTage = imageTage;
    //设置代理
    downloadIamge.delegate = self;
    //将操作添加到队列
    [self.queue addOperation:downloadIamge];
}
#pragma mark - 下载图片的代理方法
-(void)getImage:(UIImage *)image operation:(DownloadImageOperation *)operation imageTag:(NSInteger)imageTag{
    
    RecommendTableViewCell*cell = [self.tableView cellForRowAtIndexPath:operation.indexPath];
    RecommendTableViewCell_ThreeImage * cell1 = [self.tableView cellForRowAtIndexPath:operation.indexPath];
    if (cell.image.tag == imageTag) {
        cell.image.image = image;
    } else if(cell1.leftImage.tag == imageTag){
        cell1.leftImage.image = image;
    }else if (cell1.middleImage.tag == imageTag){
        cell1.middleImage.image = image;
    }else if (cell1.rightImage.tag == imageTag){
        cell1.rightImage.image = image;
    }else{
        NSLog(@"无图片");
        return;
    }
}

#pragma mark - 懒加载
//存放model的字典懒加载
-(NSMutableArray *)allDataArray
{
    if (!_allDataArray) {
        _allDataArray = [[NSMutableArray alloc] init];
    }
    return _allDataArray;
}
//队列懒加载
-(NSOperationQueue *)queue
{
    if (!_queue) {
        _queue = [[NSOperationQueue alloc] init];
        _queue.maxConcurrentOperationCount = 8;
    }
    return _queue;
}

//存储刷新数据的字典的懒加载
-(NSMutableArray *)refreshDataArr{
    if (!_refreshDataArr) {
        _refreshDataArr= [[NSMutableArray alloc] init];
    }
    return _refreshDataArr;
}

//刷新控制器的懒加载
//-(UIRefreshControl *)refrechC{
//    if (!_refrechC) {
//        _refrechC=[[UIRefreshControl alloc] init];
//    }
//    return _refrechC;
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
